use rbatis::{field_name, Page, PageRequest};
use crate::${{moduleName}}::domain::vo::${{className}}VO;
use crate::${{moduleName}}::domain::dto::${{className}}PageDTO;
use crate::${{moduleName}}::domain::mapper::${{moduleName}}_${{business_name}}::${{className}};
use crate::error::Error;
use crate::error::Result;
use crate::{export_excel_service, pool, remove_batch};


pub struct ${{className}}Service {}

impl ${{className}}Service {
    pub async fn page(&self, arg: &${{className}}PageDTO) -> Result<Page<${{className}}>> {
        let data = ${{className}}::select_page(pool!(), &PageRequest::from(arg), arg).await?;

        Ok(data)
    }

    pub async fn detail(&self, ${{pkColumn.columnName}}: &str) -> Result<${{className}}> {
        let  ${{business_name}} =
            ${{className}}::select_by_column(pool!(), field_name!(${{className}}.${{pkColumn.columnName}}), ${{pkColumn.columnName}})
                .await?
                .into_iter()
                .next()
                .ok_or_else(|| Error::from(format!("不存在:{:?} ！", ${{pkColumn.columnName}})))?;
        Ok( ${{business_name}})
    }

    pub async fn add(&self, ${{business_name}}: ${{className}}) -> Result<u64> {
        let result = Ok(${{className}}::insert(pool!(), &${{business_name}}).await?.rows_affected);
        result
    }

    pub async fn update(&self, ${{business_name}}: ${{className}}) -> Result<u64> {
        let result = ${{className}}::update_by_column(pool!(), &${{business_name}}, "${{pkColumn.columnName}}").await;
        Ok(result?.rows_affected)
    }

    pub async fn remove(&self, ${{pkColumn.columnName}}: &str) -> Result<u64> {
        {% if tableOptions.softDelete %}
         let r = pool!()
                    .exec(
                        "update ${{tableName}} set ${{tableOptions.softDeleteColumn}} = '2' where ${{pkColumn.columnName}} = ?",
                        vec![rbs::to_value!(${{pkColumn.columnName}})],
                    )
                    .await?;
         {% else %}
         let targets = ${{className}}::select_by_column(pool!(), "${{pkColumn.columnName}}", ${{pkColumn.columnName}}).await?;
         let r = ${{className}}::delete_by_column(pool!(), "${{pkColumn.columnName}}", ${{pkColumn.columnName}}).await?;
         if r.rows_affected > 0 {
             //copy data to trash
             use crate::context::CONTEXT;
             CONTEXT
                 .sys_trash_service
                 .add("${{moduleName}}_${{business_name}}", &targets)
                 .await?;
         }

        {% endif %}
        Ok(r.rows_affected)
    }
    remove_batch!(${{pkColumn.columnName}}s);
    export_excel_service!(${{className}}PageDTO, ${{className}}VO, ${{className}}::select_page);
}
